<template>
    <div id='wrap'>
        <h1>effectScope()案例</h1>
        <button @click="runtimer1Scpoe">runtimer1Scpoe</button>
        <button @click="stoptimer1Scope">stoptimer1Scope</button>

        <button @click="ganR">干扰</button>
    </div>
</template>
<script lang='ts'>
export default {
    name: 'vue',
}
</script>
<script lang='ts' setup>
import { EffectScope, effectScope, ref, h, type Ref, isRef, reactive, isReactive, readonly, isReadonly, toRef, toRefs, unref, isProxy, onScopeDispose, getCurrentScope } from 'vue';

function useTimer(): EffectScope {
    const scope = effectScope()
    return scope
}
function srun(scope: EffectScope, step = 1000): { time: Ref<number> } {
    const time = ref(0);
    let interval: ReturnType<typeof setInterval>;
    scope.run(() => {
        //开启定时器
        interval = setInterval(() => {
            console.log(time.value);
            time.value++
        }, step)
        onScopeDispose(() => {
            clearInterval(interval);
            console.log('计时器停止，资源被清理');
        })
    })
    return { time }
}

const rac = reactive<Ref<number>[]>([]);

const time1 = useTimer();

const runtimer1Scpoe = () => {
    const { time } = srun(time1);
    rac.push(time);
}

const stoptimer1Scope = () => {
    time1.stop();
}

const ganR = () => {
    if (rac.length > 0) {
        rac[0].value = 2000;
    }
} 
</script>
<style lang='scss'>
@use '@/assets/common.scss';
</style>